import jwt
import datetime
from  django.conf import settings
header = {
    'alg': 'HS256', #加密算法
    'typ': 'JWT' #令牌类型
}
#密钥，这个应该保持安全  ，不要泄露
SECRET_KEY = settings.SECRET_KEY

class ToolJWT:
    #生成token
    #参数 user 为一个字典 {id:username}
    def gettoken(self,user):
        payload = {
            'userid': user.get('id'),
            'username': user.get('username'),
            'exp': datetime.datetime.now() + datetime.timedelta(hours=2)#设置过期时间
        }
        #生成token
        return jwt.encode(payload, SECRET_KEY, algorithm='HS256',headers=header)
    #验证token
    def checktoken(self,token):
            payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'],headers=header)
            return payload

# token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3MzAzMTA2NjV9.YWVODaNbx0Wtk2_vbf_eWhrT5APIx3jro7OrBunXJsc'
tooljwt = ToolJWT()
# print(tool.gettoken({'id':1,'username':'admin'}))
# print(tooljwt.checktoken(token))
